import _ from 'lodash';
import { message } from 'antd';
import { warehouseLoc, warehouse, area, del, create, edit } from '../services/warehouseLoc';
import { user } from '../utils/user';


export default {
  namespace: 'warehouseLoc',
  state: {
    warehouseLocs: [],
    total: 20,
    warehouses: [],
    areas: [],
    defaultWid: null,
  },
  effects: {
    *query({ payload }, { put }) {
      // 获取用户信息
      const info = yield user();
      const args = _.cloneDeep(payload);
      if (!args.wid) {
        args.wid = info.wid;
      }
      // 处理空字符串，或者是undefined的属性
      Object.keys(args).forEach((key) => {
        if (!args[key]) {
          delete args[key];
        }
      });

      const locs = yield warehouseLoc(args);
      yield put({
        type: 'save',
        payload: {
          warehouseLocs: locs.list,
          total: locs.total,
          defaultWid: info.wid, // 用户自己管理的仓库
        },
      });

      yield put({
        type: 'queryArea',
        payload: {
          wid: args.wid,
        },
      });
    },
    *queryWarehouse(states, { put }) {
      const info = yield user();
      try {
        const warehouses = yield warehouse(info.wid);
        yield put({
          type: 'save',
          payload: {
            warehouses,
            defaultWid: info.wid,
          },
        });
      } catch (e) {
        message.error(`获取信息失败,请刷新重试:${e.message}` || e);
      }
    },
    *queryArea({ payload: { wid }, ...rest }, { put, select }) {
      const state = yield select();
      const areas = _.get(state, 'warehouseLoc.areas');
      try {
        const data = yield area(wid);
        areas[wid] = data;
        yield put({
          type: 'save',
          payload: {
            areas,
          },
        });
      } catch (e) {
        message.error(`获取信息失败,请刷新重试:${e.message}` || e);
      }
    },
    *del({ payload: { wlid, onEnd } }) {
      let args = [];
      if (!wlid) {
        return onEnd('缺少id');
      }
      if (wlid.constructor !== Array) {
        args.push(wlid);
      } else {
        args = wlid;
      }
      yield del(args);
      onEnd();
    },
    *create({ payload: { query, onEnd } }) {
      const args = _.cloneDeep(query);
      const info = yield user();
      // 设置wid的默认值
      args.wid = args.wid || info.wid;
      try {
        yield create(args);
      } catch (e) {
        return onEnd(e.message || e);
      }
      onEnd();
    },
    *edit({ payload: { query, onEnd } }) {
      const args = _.cloneDeep(query);
      try {
        yield edit(args);
      } catch (e) {
        return onEnd(e.message || e);
      }
      onEnd();
    },
  },
  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },
};
